#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int start(int sock) {
    if(sock < 0) {
        return -1;
    }

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(9999);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    
    int opt = 1;
    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    if(bind(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        return -1;
    }

    if(listen(sock, 5) < 0) {
        return -1;
    }

    return 0;
}


int main()
{
    int server_sock = socket(AF_INET, SOCK_STREAM, 0);
    int ret = start(server_sock);
    if(ret == -1) {
        perror("start");
        return 1;
    }
    printf("TCP服务器启动成功\n");

    //等待tcp客户端连接
    struct sockaddr_in client_addr;
    socklen_t len;
    int client_sock = accept(server_sock, (struct sockaddr*)&client_addr, &len);  
    if(client_sock < 0) {
        printf("客户端连接失\n");
        return 2;
    }

    printf("客户端连接成功, 客户端的文件描述符是：%d\n", client_sock);
    return 0;
}
